#include <stdio.h>
#include <unistd.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/types.h>

union semun
{
    int val;
};

int main()
{
    extern int i;
    int semid = semget(5678,3,0777); 
    int semid2=semget(1234,3,0777);  
    int semid3=semget(1245,3,0777); 
    union semun mysem;
    mysem.val = 0;

    int ctlret = semctl(semid2,0,SETVAL,mysem);
    ctlret = semctl(semid,0,SETVAL,mysem);
    ctlret=semctl(semid3,0,SETVAL,mysem);

    struct sembuf mybuf1;
    mybuf1.sem_num = 0;
    mybuf1.sem_flg = 0;
    mybuf1.sem_op =1;//释放信号量
    struct sembuf mybuf2;
    mybuf2.sem_num=0;
    mybuf2.sem_flg=0;
    mybuf2.sem_op=-1;
    //取一个信号

    pid_t pid = fork();
    
    if(pid>0)
    {
        pid_t pid2=fork();
        if (pid2==0){
            while(1){
                 semop(semid2,&mybuf2,1);
            printf("子线程1卖出了第%d张机票！",i);
            semop(semid3,&mybuf1,1);
            }

        }else{
        while(i<100)
        {
            sleep(100);
            i++;
            if(i%2==0){
            semop(semid,&mybuf1,1);
            }else{
                semop(semid2,&mybuf1,1);
            }
            semop(semid3,&mybuf2,1);
        }
        }
    }
    if(pid==0)
    {
        while(1){
            semop(semid,&mybuf2,1);
        printf("子线程2卖出了第%d张机票！",i);
        semop(semid,&mybuf1,1);
        }
        
    }
    return 0;
}

